In C#, attributes add metadata (data about data) to your code. They are a powerful way to annotate classes, methods, properties, and other program elements with additional information that can be used by the compiler, runtime, or tools.
What Are Attributes?
Attributes provide descriptive information about your code. For example, you can mark a method as obsolete, specify how a property should be serialized, or define custom metadata for your own tools.
Real-Life Analogy:
Think of attributes as sticky notes on your code — they don’t change the code's logic directly but provide useful instructions.
Basic Syntax
[AttributeName]
With parameters
[AttributeName(param1, param2)]
Commonly Used Attributes in C#
| Attribute | Description |
|---|---|
[Obsolete] |
Marks code as outdated or deprecated |
[Serializable] |
Allows an object to be serialized |
[NonSerialized] |
Prevents a field from being serialized |
[DllImport] |
Used for interoperability with native DLLs |
[DebuggerStepThrough] |
Skips method when debugging |
[Required] |
Used in validation (usually with MVC / Data Annotations) |
[Display(Name="")] |
Sets a friendly name for a property |
Example 1: [Obsolete]
[Obsolete("Use NewMethod() instead")]
public void OldMethod()
{
Console.WriteLine("This method is obsolete.");
}
Calling OldMethod() will show a compiler warning.
Example 2: [Serializable]
[Serializable]
public class Person
{
public string Name;
public int Age;
}
Example 3: Data Annotation Attributes (in ASP.NET MVC)
public class User
{
[Required]
[Display(Name = "Full Name")]
public string Name { get; set; }
[Range(18, 100)]
public int Age { get; set; }
}
[Required]makes sureNameis not null or empty.[Display]changes the label name.[Range]sets valid value boundaries.
Creating Custom Attributes
You can define your own attributes by extending System.Attribute.
public class AuthorAttribute : Attribute
{
public string Name;
public AuthorAttribute(string name)
{
Name = name;
}
}
Use it like:
[Author("John Doe")]
public class SampleClass
{
}
Reading Attributes via Reflection
Attributes can be accessed at runtime using reflection.
Type type = typeof(SampleClass);
object[] attrs = type.GetCustomAttributes(false);
foreach (var attr in attrs)
{
Console.WriteLine(attr);
}
Summary
| Feature | Description |
|---|---|
| What is it? | Metadata you attach to your code |
| Usage | With square brackets above code elements |
| Purpose | Inform compiler, tools, or at runtime |
| Custom? | Yes, you can create your own attributes |
| Reflection | Used to read attribute data at runtime |
Attributes make your code more informative, maintainable, and flexible. From marking code as obsolete to controlling serialization, they play a crucial role in many frameworks — especially in ASP.NET, Entity Framework, and Xamarin.
Leave Comment